package com.mypack.crm.service.contact.impl;

import com.github.pagehelper.PageHelper;
import com.mypack.crm.constants.EnumDeleteFlag;
import com.mypack.crm.constants.EnumStatus;
import com.mypack.crm.dto.contact.ContactDTO;
import com.mypack.crm.dto.contact.ContactSearchDTO;
import com.mypack.crm.entity.CrmContact;
import com.mypack.crm.mapper.ContactMapper;
import com.mypack.crm.service.contact.ContactService;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ContactServiceImpl implements ContactService {

    @Autowired
    private ContactMapper contactMapper;
    @Autowired
    private MapperFacade mapperFacade;

    @Override
    public void add(ContactDTO contactDTO) {
        contactDTO.setDeleteFlag(EnumDeleteFlag.NO.getCode());
        contactDTO.setCreateTime(new Date());
        contactDTO.setStatus(EnumStatus.ACTIVE.getCode());
        CrmContact crmContact = mapperFacade.map(contactDTO, CrmContact.class);
        contactMapper.insert(crmContact);
    }

    @Override
    public void update(ContactDTO contactDTO) {
        if (contactDTO.getId() == null) {
            return;
        }
        CrmContact crmContact = mapperFacade.map(contactDTO, CrmContact.class);
        crmContact.setUpdateTime(new Date());
        contactMapper.updateById(crmContact);
    }

    @Override
    public void delete(Integer id) {
        ContactDTO contactDTO = new ContactDTO();
        contactDTO.setId(id);
        contactDTO.setDeleteFlag(EnumDeleteFlag.YES.getCode());
        update(contactDTO);
    }

    @Override
    public List<ContactDTO> list(ContactSearchDTO searchDTO, boolean isPage) {

        if (isPage) {
            PageHelper.startPage(searchDTO.getPageNum(), searchDTO.getPageSize());
        }

        return contactMapper.listContact(searchDTO);
    }
}
